// 比赛管理模块
class GameManager {
    constructor() {
        this.games = [];
        this.loadGames();
        this.bindEvents();
        this.updateGameList();
    }

    // 从localStorage加载比赛数据
    loadGames() {
        const savedGames = localStorage.getItem('games');
        this.games = savedGames ? JSON.parse(savedGames) : [];
    }

    // 保存比赛数据到localStorage
    saveGames() {
        localStorage.setItem('games', JSON.stringify(this.games));
    }

    // 更新比赛列表显示
    updateGameList() {
        const tbody = document.querySelector('#match-list-table tbody');
        if (!tbody) return;

        if (this.games.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="text-muted">暂无比赛信息</td></tr>';
            return;
        }

        // 按日期降序排序
        const sortedGames = [...this.games].sort((a, b) => new Date(b.date) - new Date(a.date));

        tbody.innerHTML = sortedGames.map(game => `
            <tr>
                <td>${new Date(game.date).toLocaleDateString()}</td>
                <td>${game.playerA.name}</td>
                <td>${game.winner === game.playerA.id ? '胜' : '负'}</td>
                <td>${game.playerB.name}</td>
                <td>${game.winner === game.playerA.id ? game.playerA.name : game.playerB.name}</td>
            </tr>
        `).join('');

        // 强制触发DOM更新
        tbody.style.display = 'none';
        setTimeout(() => tbody.style.display = '', 0);
    }

    // 清空比赛记录
    clearGames() {
        // 清空比赛记录
        this.games = [];
        this.saveGames();
        this.updateGameList();

        // 重置所有选手的积分和比赛次数
        const players = playerManager.getAllPlayers();
        players.forEach(player => {
            player.score = 0;
            player.gamesPlayed = 0;
        });
        playerManager.savePlayers();
        playerManager.updatePlayerList();
    }

    // 导出比赛数据到文件
    exportGames() {
        const data = JSON.stringify(this.games, null, 2);
        const blob = new Blob([data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'games.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 导入比赛数据
    importGames(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    this.games = data;
                    this.saveGames();
                    this.updateGameList();
                    resolve();
                } catch (error) {
                    reject('文件格式错误');
                }
            };
            reader.onerror = () => reject('读取文件失败');
            reader.readAsText(file);
        });
    }

    // 绑定事件处理
    bindEvents() {
        // 添加导入导出按钮到表格标题栏
        const cardHeader = document.querySelector('.card-header:last-child');
        if (cardHeader) {
            const buttonGroup = document.createElement('div');
            buttonGroup.className = 'btn-group me-2';
            buttonGroup.innerHTML = `
                <button class="btn btn-sm btn-primary export-games">导出比赛</button>
                <label class="btn btn-sm btn-success import-games">
                    导入比赛
                    <input type="file" accept=".json" style="display: none;">
                </label>
            `;
            cardHeader.insertBefore(buttonGroup, cardHeader.firstChild);

            // 绑定导出按钮事件
            const exportBtn = cardHeader.querySelector('.export-games');
            exportBtn.addEventListener('click', () => this.exportGames());

            // 绑定导入按钮事件
            const importInput = cardHeader.querySelector('input[type="file"]');
            importInput.addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (file) {
                    try {
                        await this.importGames(file);
                        alert('比赛数据导入成功');
                    } catch (error) {
                        alert(error);
                    }
                    importInput.value = '';
                }
            });
        }

        // 绑定清空比赛按钮事件
        const clearGamesBtn = document.querySelector('#clear-games-btn');
        if (clearGamesBtn) {
            clearGamesBtn.addEventListener('click', () => {
                if (confirm('确定要清空所有比赛记录吗？这将同时重置所有选手的积分。')) {
                    this.clearGames();
                }
            });
        }

        const gameForm = document.querySelector('#modal-report');
        if (!gameForm) return;

        const dateInput = gameForm.querySelector('input[type="date"]');
        const playerInputs = gameForm.querySelectorAll('.input-group input[type="text"]');
        const playerRadios = gameForm.querySelectorAll('.input-group input[type="radio"]');

        // 填充选手下拉菜单
        const updatePlayerSelects = () => {
            const players = playerManager.getAllPlayers();
            playerSelects.forEach(select => {
                select.innerHTML = '<option value="">选择选手</option>' +
                    players.map(player => `<option value="${player.id}">${player.name}</option>`).join('');
            });
        };

        // 初始化Bootstrap模态框
        const modal = new bootstrap.Modal(gameForm, {
            backdrop: 'static',
            keyboard: false
        });

        // 监听模态框显示事件
        gameForm.addEventListener('shown.bs.modal', () => {
            // 设置日期默认值为今天
            dateInput.valueAsDate = new Date();
            // 聚焦到日期输入框
            dateInput.focus();
        });

        // 监听模态框隐藏事件
        gameForm.addEventListener('hidden.bs.modal', () => {
            // 重置表单
            dateInput.value = '';
            playerInputs.forEach(input => input.value = '');
            playerRadios.forEach(radio => radio.checked = false);
        });

        // 添加关闭按钮事件监听
        const closeButtons = gameForm.querySelectorAll('[data-bs-dismiss="modal"]');
        closeButtons.forEach(button => {
            button.addEventListener('click', () => {
                modal.hide();
            });
        });

        // 初始化选手选择下拉列表
        playerInputs.forEach(input => {
            const datalist = document.createElement('datalist');
            datalist.id = 'player-list-' + Math.random().toString(36).substr(2, 9);
            input.setAttribute('list', datalist.id);
            document.body.appendChild(datalist);

            input.addEventListener('focus', () => {
                const players = playerManager.getAllPlayers();
                datalist.innerHTML = players.map(player =>
                    `<option value="${player.name}" data-id="${player.id}">`
                ).join('');
            });
        });

        // 保存比赛记录
        const saveGameBtn = gameForm.querySelector('.btn-primary');
        saveGameBtn.addEventListener('click', () => {
            const date = dateInput.value;
            const playerAInput = playerInputs[0];
            const playerBInput = playerInputs[1];
            const winnerRadio = Array.from(playerRadios).find(radio => radio.checked);

            // 验证输入
            if (!date) {
                alert('请选择比赛日期');
                return;
            }

            if (!playerAInput.value || !playerBInput.value) {
                alert('请选择比赛选手');
                return;
            }

            if (playerAInput.value === playerBInput.value) {
                alert('不能选择相同的选手');
                return;
            }

            if (!winnerRadio) {
                alert('请选择获胜选手');
                return;
            }

            // 获取选手信息
            const players = playerManager.getAllPlayers();
            const playerA = players.find(p => p.name === playerAInput.value);
            const playerB = players.find(p => p.name === playerBInput.value);

            if (!playerA || !playerB) {
                alert('请选择有效的选手');
                return;
            }

            // 创建新比赛记录
            const newGame = {
                id: Date.now().toString(),
                date: date,
                playerA: {
                    id: playerA.id,
                    name: playerA.name
                },
                playerB: {
                    id: playerB.id,
                    name: playerB.name
                },
                winner: winnerRadio.closest('.input-group').querySelector('input[type="text"]').value === playerA.name ? playerA.id : playerB.id
            };

            // 更新比赛记录
            this.games.push(newGame);
            this.saveGames();

            // 更新选手积分
            const nonParticipants = players.filter(p => p.id !== playerA.id && p.id !== playerB.id).map(p => p.id);
            const loser = newGame.winner === playerA.id ? playerB.id : playerA.id;
            playerManager.updatePlayerScores(newGame.winner, loser, nonParticipants);

            // 更新列表显示
            this.updateGameList();
            playerManager.updatePlayerList();

            // 关闭模态框
            modal.hide();
        });
    }
}

// 初始化比赛管理器
const gameManager = new GameManager();